package main

import (
	"fmt"
	"sync"
)

// 异步任务
func main() {

	var wg sync.WaitGroup
	//运行一个 go
	wg.Add(2)
	resultChan := make(chan string)
	resultc := make(chan int)

	go Run(&wg, "消息", resultc, resultChan)
	go Run(&wg, "消--息", resultc, resultChan)
	go func() {
		wg.Wait()
		close(resultChan) // 关闭 channel
		close(resultc)    // 关闭 channel
	}()
	// 监听进度和结果
	for {
		select {
		case progress, ok := <-resultChan:
			if !ok {
				//有错误设置关闭
				resultChan = nil
				break
			}
			if progress == "消息-5" {
				fmt.Println("成功到5了", progress)
			} else {
				fmt.Println("成功到了", progress)
			}

		case result, ok := <-resultc:
			fmt.Println("--:", result)
			if !ok {
				//有错误设置关闭
				resultc = nil
				break
			}
		}
		// 如果两个 channel 都关闭了，退出循环
		if resultChan == nil && resultc == nil {
			break
		}
	}

}

func Run(wg *sync.WaitGroup, name string, result chan<- int, resultChan chan<- string) {
	defer wg.Done()
	for i := 0; i <= 10; i++ {
		// 发送进度更新
		resultChan <- fmt.Sprintf("%s-%d", name, i)
		result <- i
	}
}
